const path = require('path');
const fs = require('fs');

const util = require('./util');

const basePath = './dist/zh-cn';
const sideBarPath = './dist/common/sidebar.md';

/**
 * 同步获取文件属性 是否文件/文件夹
 * @param dir
 * @param filename
 * @returns {Promise<Object>}
 */
function getStatSync(dir, filename) {
  let pathname = path.join(dir, filename);
  return new Promise((resolve, reject) => {
    fs.stat(pathname, async (err, stats) => {
      if (err) return console.log('获取文件stats失败');
      if (stats.isDirectory()) {
        if (['common'].indexOf(filename) === -1) {
          resolve({
            type: 'directory',
            filename,
            // files: await mapDir(pathname)
          })
        }
      } else if (stats.isFile()) {
        let content = fs.readFileSync(pathname, 'utf-8');
        resolve({
          type: 'file',
          filename,
          content
        })
      }
    });
  });
}

/**
 * 遍历文件夹
 * @param dir
 * @returns {Promise<Object>}
 */
async function mapDir(dir) {
  return new Promise((resolve, reject) => {
    fs.readdir(dir, async (err, files) => {
      if (err) return console.error(err);
      let result = [];
      await util.syncQueue(files, async filename => {
        let pathname = path.join(dir, filename);
        let data = await getStatSync(dir, filename);
        if (data.type === 'directory') {
          result.push({
            type: 'directory',
            filename,
            files: await mapDir(pathname)
          });
        } else if (data.type === 'file') {
          result.push(data);
        }
      }, async () => {
      }, 0);
      resolve(result);
    });
  });
}

/**
 * 写到文件
 * @param data
 * @param pathName
 * @returns {string}
 */
function makeContent(data, pathName = 'zh-cn') {
  let content = '';
  for (let i in data) {
    let v = data[i];
    if (v.type === 'directory') {
      content += `- ${v.filename}\n`;
      content += makeContent(v.files, [pathName, v.filename].join('/'));
      content += `\n`;
    } else if (v.type === 'file') {
      content += `   - [${v.filename.replace(/([\s\S]*)\.md/i, '$1')}](${pathName}/${v.filename})\n`;
      // content += v.content;
    }
  }
  return content;
}

/**
 * 执行
 */
mapDir(basePath).then(data => {
  console.log(data);
  fs.writeFileSync(sideBarPath, makeContent(data));
});


